<?php

namespace App\Http\Controllers\Api\Admin;

use App\CustomerClue;
use App\CustomerServiceImgs;
use App\CustomerServiceRecord;
use App\CustomerXStaff;
use App\Http\Services\AdminManager;
use App\Http\Services\CommonManager;
use App\Http\Services\FileManager;
use App\Staff;
use App\User;
use App\UserInfo;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class CrmController extends Controller
{
    public function setCustomerClue(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        $id             = $request->input('id');
        $customer_name  = $request->input('customer_name');
        $contact        = $request->input('contact');
        $wechat         = $request->input('wechat');
        $province       = $request->input('province');
        $city           = $request->input('city');
        $area           = $request->input('area');
        $address        = $request->input('address');
        $is_invalid     = $request->input('is_invalid');
        $remark         = $request->input('remark');

        $contactExists = CustomerClue::whereContact($contact)->first();

        if ($id){
            $data = CustomerClue::whereId($id)->first();
            if (!$data){
                if($contactExists)
                    return response()->json(['level' => 'error','message' => '该联系方式已被使用']);

                $data = new CustomerClue();
                $data->creator_id = $adminUser->id;
            }else{
                if($contactExists && ($contactExists->id != $data->id))
                    return response()->json(['level' => 'error','message' => '该联系方式已被使用']);
            }
        } else {
            if($contactExists)
                return response()->json(['level' => 'error','message' => '该联系方式已被使用']);

            $data = new CustomerClue();
            $data->creator_id = $adminUser->id;
        }

        $data->customer_name = $customer_name ?? '';
        $data->contact = $contact ?? '';
        $data->wechat  = $wechat ?? '';
        $data->province = $province ?? '';
        $data->city = $city ?? '';
        $data->area = $area ?? '';
        $data->address = $address ?? '';
        $data->is_invalid = $is_invalid ?? 0;
        $data->remark = $remark ?? '';
        $data->save();
        return response()->json(['level' => 'success','message' => '设置成功','data' => $data]);
    }
    public function setCustomerServiceStaff(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $staff_id            = $request->input('staff_id');
        $customer_clue_id    = $request->input('customer_clue_id') ?? 0;
        $userId              = $request->input('user_id') ?? 0;

        if(empty($userId) && empty($customer_clue_id))
            return response()->json(['level' => 'error','message' => '参数错误']);

        try{
            \DB::beginTransaction();
            if($userId){
                $user = User::whereId($userId)->first();
                if(!$user)
                    return response()->json(['level' => 'error','message' => '用户不存在']);

                $userInfo = UserInfo::whereUserId($user->id)->first();
                if(!$userInfo)
                    return response()->json(['level' => 'error','message' => '用户信息不存在']);

                $thisCustomer = CustomerClue::whereUserId($user->id)->first();
                if(!$thisCustomer){
                    $thisCustomer = new CustomerClue();
                    $thisCustomer->user_id       = $user->id;
                    $thisCustomer->customer_name = $userInfo->realname ? $userInfo->realname : $userInfo->nickname;
                    $thisCustomer->contact       = $user->phone ?? '';
                    $thisCustomer->save();
                }
            }else{
                $thisCustomer = CustomerClue::whereId($customer_clue_id)->first();
                if (!$thisCustomer){
                    \DB::rollBack();
                    return response()->json(['level' => 'error','message' => '客户线索不存在','data' => '']);
                }
            }

            $record = CustomerXStaff::whereCustomerCluesId($thisCustomer->id)->first();
            if (!$record){
                $record = new CustomerXStaff();
                $record->customer_clues_id = $thisCustomer->id;
            }
            $record->staff_id = $staff_id ? $staff_id : 0;
            $record->save();
            if ($record->staff_id){
                $thisCustomer->is_select = 1;
            } else {
                $thisCustomer->is_select = 0;
            }
            $thisCustomer->save();
            \DB::commit();
        } catch (\Exception $exception){
            \DB::rollBack();
            return response()->json(['level' => 'error','message' =>'操作失败：'.$exception->getMessage(),'data' =>'']);
        }

        return response()->json(['level' => 'success','message' => '设置成功','data' => $record]);
    }
    public function delCustomerClue(Request $request)
    {
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if (!$adminUser)
            return response()->json(['level' => 'error', 'message' => '请先登录！', 'data' => 'no_login']);
        $id = $request->input('id');
        if (!$id)
            return response()->json(['level' => 'error', 'message' => '参数错误', 'data' => '']);
        $data = CustomerClue::whereId($id)->first();
        if (!$data)
            return response()->json(['level' => 'error', 'message' => '数据不存在', 'data' => '']);
        $data->delete();
        return response()->json(['level' => 'success', 'message' => '设置成功', 'data' => $data]);
    }
    public function getCustomerClueList(Request $request){
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        if(!empty($adminUser->staff_key)){
            $staff = Staff::whereStaffKey($adminUser->staff_key)->first();
        }else{
            $staff = null;
        }

        $page           = $request->input('page');
        $limit          = $request->input('limit');
        $is_invalid     = $request->input('is_invalid');
        $page_info      = [
            'page'=>$page,
            'limit'=>$limit
        ];
        $page = $page - 1;

        /** @var CustomerClue $data */
        $data = CustomerClue::where('id','>',0);

        if($staff){
            $customerIdArr = CustomerXStaff::whereStaffId($staff->id)->pluck('customer_clues_id')->toArray();

            $data = $data->whereIn('id',$customerIdArr);
        }

        $page_info['total'] = $data->count();

        $data = $data->orderByDesc('id')
            ->offset($page * $limit)
            ->limit($limit)
            ->get();
        if (count($data) > 0){
            foreach ($data as $item){
                $item->now_staff = CustomerXStaff::getCustomerNowStaff($item->id);
                $item->creator_name = '管理员';
                $item->user_info = CommonManager::getUserBasicInfo($item->user_id);
            }
        }
        return response()->json(['level' => 'success','message' => '设置成功','data' => $data,'page_info'=>$page_info]);
    }

    public function getCustomerServiceRecord(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        $page           = $request->input('page');
        $limit          = $request->input('limit');
        $customer_clues_id = $request->input('customer_clues_id');
        $staff_id       = $request->input('staff_id');

        $page_info      = [
            'page'=>$page,
            'limit'=>$limit
        ];
        $page = $page - 1;
        /** @var CustomerServiceRecord $data */
        $data = CustomerServiceRecord::where('id','>',0);
        if ($customer_clues_id){
            $data =$data->whereCustomerCluesId($customer_clues_id);
        }
        if ($staff_id){
            $data =$data->whereStaffId($staff_id);
        }
        $page_info['total']=$data->count();
        $data = $data
            ->orderByDesc('id')
            ->offset($page * $limit)
            ->limit($limit)
            ->get();
        if (count($data) > 0){
            foreach ($data as $item){
                $item->staff_info = Staff::getStaffInfo($item->staff_id);
                $item->customer_info = CustomerClue::getCustomerInfo($item->customer_clues_id);
                $item->video_url = FileManager::getVideoUrl($item->video_id);
                $item->Img_list    = CustomerServiceImgs::getServicesImgUrlArray($item->id);
            }
        }
        return response()->json(['level' => 'success','message' => '设置成功','data' => $data,'page_info'=>$page_info]);
    }

    /**
     * 取消跟进人
     * @return string
     * @throws \Exception
     */
    public function cancelFollowUp(){
        $customerXStaffList = CustomerXStaff::all();
        if(count($customerXStaffList) > 0){
            foreach ($customerXStaffList as $customerXStaff) {
                $customerServiceRecord = CustomerServiceRecord::whereCustomerCluesId($customerXStaff->customer_clues_id)->whereStaffId($customerXStaff->staff_id)->orderByDesc('id')->first();
                if($customerServiceRecord && $customerServiceRecord->updated_at->timestamp <= time() - (86400 * 30)){
                    $customerXStaff->delete();
                }

                if(!$customerServiceRecord && $customerXStaff->created_at->timestamp <= time() - (86400 * 30)){
                    $customerXStaff->delete();
                }
            }
        }

        return 'success';
    }
}
